import * as THREE from 'three'

let scene: THREE.Scene
let camera: THREE.PerspectiveCamera
let renderer: THREE.WebGLRenderer
let particles: THREE.Points

export function initBackground() {
  // 初始化场景
  scene = new THREE.Scene()
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
  renderer = new THREE.WebGLRenderer({ 
    canvas: document.getElementById('bg-canvas') as HTMLCanvasElement,
    alpha: true,
    antialias: true
  })
  
  renderer.setSize(window.innerWidth, window.innerHeight)
  renderer.setPixelRatio(window.devicePixelRatio)
  scene.background = new THREE.Color(0x0a0a1a)

  // 创建粒子系统
  const geometry = new THREE.BufferGeometry()
  const positions = new Float32Array(2000 * 3)
  
  for (let i = 0; i < 2000; i++) {
    positions[i * 3] = (Math.random() - 0.5) * 100
    positions[i * 3 + 1] = (Math.random() - 0.5) * 100
    positions[i * 3 + 2] = (Math.random() - 0.5) * 100
  }
  
  geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3))
  
  const material = new THREE.PointsMaterial({
    color: 0x00ffff,
    size: 0.15,
    transparent: true,
    opacity: 0.8,
    sizeAttenuation: true
  })
  
  particles = new THREE.Points(geometry, material)
  scene.add(particles)
  
  camera.position.z = 50
}

export function animateBackground() {
  function animate() {
    requestAnimationFrame(animate)
    particles.rotation.y += 0.0005
    renderer.render(scene, camera)
  }
  animate()
}